package main

import (
	"fmt"
	"gitee.com/libbylg/pkgr/repo"
	"strings"
)

type CmdUninstallOptions struct {
	Force bool   // 强制删除
	Label string // 指定需要删除的模块版本匹配方式
}

// NewCmdUninstallOptions 用于加载命令行参数
// pkgr uninstall LABEL [--force|-f]
func NewCmdUninstallOptions(argv []string) (*CmdUninstallOptions, error) {
	// 检查参数数量
	if len(argv) < 3 {
		return nil, fmt.Errorf("the required parameter is missing, try -h for help")
	}

	// 初始化默认值
	opt := &CmdUninstallOptions{
		//Force: false,
		Label: "",
	}

	// 读取选项
	for index := 2; index < len(argv); index++ {
		//if argv[index] == "--Force" || argv[index] == "-f" {
		//	opt.Force = true
		//	continue
		//}

		// 遇到无法识别的选项
		if strings.HasPrefix(argv[index], "-") {
			return nil, fmt.Errorf("unsupported options `%v'", argv[index])
		}

		// 识别 PATTERN 参数
		if len(opt.Label) == 0 {
			opt.Label = argv[index]
			continue
		}

		return nil, fmt.Errorf("unsupported option `%v'", argv[index])
	}

	// Label 参数是必须的
	if opt.Label == "" {
		return nil, fmt.Errorf("the module Label to be uninstalled is missing")
	}

	return opt, nil
}

// CmdUninstall 删除已经安装的包
// thpkg uninstall LABEL
func CmdUninstall(argv []string) int {
	opt, err := NewCmdUninstallOptions(argv)
	if err != nil {
		ERROR("Load option for `%v' failed: %v", "uninstall", err.Error())
		return 1
	}

	if !repo.PathIsDir(repo.DEVREPO) {
		ERROR("The environment variable `DEVREPO' is missing")
		return 1
	}

	moduleLabel, err := repo.ParseModuleLabel(opt.Label)
	if err != nil {
		ERROR("Invalid module label `%v': %v", opt.Label, err.Error())
		return 1
	}

	// 如果没有安装，那么不要干啥，直接返回即可
	if !repo.IsInstalled(moduleLabel.ModuleName, moduleLabel.ModuleVersion) {
		INFOR("Module `%v' has not been installed yet", moduleLabel.String())
		return 0
	}

	err = repo.MoveInstalledToRecycle(moduleLabel.ModuleName, moduleLabel.ModuleVersion)
	if err != nil {
		INFOR("Uninstall module `%v' failed: %v", moduleLabel.String(), err)
		return 1
	}

	INFOR("Uninstall module `%v' success", moduleLabel.String())
	return 0
}
